/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.document.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.je.common.base.document.ContentTypeSuffixEnum;
import com.je.common.base.document.MetadataEnum;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.util.*;
import com.je.document.exception.DocumentException;
import com.je.document.exception.DocumentExceptionEnum;
import com.je.document.model.FileBO;
import com.je.document.model.FileUpload;
import com.je.document.service.DocumentBusService;
import com.je.document.service.file.FileRelService;
import com.je.document.util.MetadataUtil;
import com.je.document.vo.FileVO;
import com.je.servicecomb.InputstreamContentTypePart;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 文档controller
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/8/27
 */
@RestController
@RequestMapping(value = "/je/document")
public class DocumentController {

    private static final Logger logger = LoggerFactory.getLogger(DocumentController.class);

    @Autowired
    private DocumentBusService documentBusService;

    @Autowired
    private MetaResourceService metaRpcService;

    @Autowired
    private FileRelService fileRelService;

    /**
     * 上传附件
     * <p>
     * 单附件多附件
     * {'uploadType':'TEMP'}
     * <p>
     * 功能附件
     * {'uploadType':'FUNC','funcCode':'XXXX','tableCode':'XXXXX','pkValue':'YYYYYY'}
     * <p>
     * 附件子功能附件
     * {'uploadType':'SUBFUNC','funcCode':'XXXX','tableCode':'XXXXX','pkValue':'YYYYYY','dicCode':'1','dicId':'1','dicName':'1'}
     * <p>
     * 流程附件
     * {'uploadType':'FLOW','funcCode':'XXXX','tableCode':'XXXXX','pkValue':'YYYYYY'}
     * <p>
     * files     文件对象列表
     * metadataStr 文件业务元数据,JSONObject格式,key范围为 MetadataEnum
     * bucket      存储空间标识
     *
     * @return BaseRespResult
     */
    @RequestMapping(value = "/file", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public BaseRespResult<List<FileVO>> file(HttpServletRequest httpServletRequest) {
        //校验是否存在文件
        List<Part> files = new ArrayList<>();
        try {
            List<Part> list = (List<Part>) httpServletRequest.getParts();
            if (list != null && list.size() > 0) {
                for (Part part : list) {
                    if (StringUtils.isNotEmpty(part.getContentType())) {
                        files.add(part);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        if (files == null || files.isEmpty()) {
            return BaseRespResult.errorResult(DocumentExceptionEnum.JE_DOC_FILE_READ_ERROR.getCode(), "未找到附件");
        }
        String bucket = StringUtil.getStringParameter(httpServletRequest, "bucket");
        if ("null".equals(bucket)) {
            bucket = null;
        }

        //用户ID
        String userId = SecurityUserHolder.getCurrentAccountRealUserId();
        //业务元数据添加租户ID
        String metadataStr = StringUtil.getStringParameter(httpServletRequest, "metadataStr");
        JSONObject metadata = new JSONObject();
        if (StringUtils.isNotBlank(metadataStr)) {
            metadata = JSON.parseObject(metadataStr);
        }

        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);
        //调用业务方法
        try {
            //保存附件
            List<FileUpload> fileUploadFiles = Lists.newArrayList();
            for (Part part : files) {
                FileUpload fileUpload = new FileUpload(part.getSubmittedFileName(),
                        part.getContentType(), part.getSize(), part.getInputStream());
                documentBusService.checkFileSuffix(fileUpload.getFileName());
                fileUploadFiles.add(fileUpload);
            }
            //保存文件并持久化业务数据
            String dir = StringUtil.getStringParameter(httpServletRequest, "dir");
            List<FileBO> fileBos = documentBusService.saveFile(fileUploadFiles, userId, metadata, bucket, dir);
            return BaseRespResult.successResult(transformVOList(fileBos));
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw (DocumentException) e;
            } else {
                throw new DocumentException("附件上传错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }
    }

    /**
     * 上传base64数据附件,参数同普通文件上传
     *
     * @param request     请求对象
     * @param metadataStr 文件业务元数据,JSONObject格式,key范围为 MetadataEnum
     * @param bucket      存储空间标识
     * @return BaseRespResult
     */
    @RequestMapping(value = "/fileBase64", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<List<FileVO>> fileBase64(HttpServletRequest request, String metadataStr, String bucket) {

        //默认文件数据字段名
        String funcUploadField = "data";

        //获取文件 示例:
        String base64Str = request.getParameter(funcUploadField);

        //获取文件名
        String fileName = request.getParameter("fileName");
        if (StringUtils.isBlank(fileName)) {
            fileName = JEUUID.uuid();
        }

        //分隔标识
        String split = "base64,";

        String[] base64StrArray = null;

        //校验是否存在文件
        if (StringUtils.isBlank(base64Str) || !base64Str.contains(split) || (base64StrArray = base64Str.split(split)).length != 2) {
            return BaseRespResult.errorResult(DocumentExceptionEnum.JE_DOC_FILE_READ_ERROR.getCode(), "未找到附件");
        }

        //文件类型
        String contentType = base64StrArray[0].replaceAll("data:", "").replaceAll(";", "");
        //文件数据
        String base64Data = base64StrArray[1];
        //字符串转byte数组
        byte[] base64ByteArray = Base64.decode(base64Data);
        //byte数组转inputStream
        ByteArrayInputStream inputStream = IoUtil.toStream(base64ByteArray);

        //业务元数据添加租户ID
        JSONObject metadata = new JSONObject();
        if (StringUtils.isNotBlank(metadataStr)) {
            metadata = JSON.parseObject(metadataStr);
        }

        //用户ID
        String userId = SecurityUserHolder.getCurrentAccountRealUser().getId();

        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        //调用业务方法
        try {
            //保存附件
            List<FileUpload> fileUploadFiles = Lists.newArrayList();
            //封装文件
            FileUpload fileUpload = new FileUpload(fileName, contentType, (long) inputStream.available(), inputStream);
            documentBusService.checkFileSuffix(fileUpload.getFileName());
            fileUploadFiles.add(fileUpload);
            //保存文件并持久化业务数据
            List<FileBO> fileBos = documentBusService.saveFile(fileUploadFiles, userId, metadata, bucket, null);

            return BaseRespResult.successResult(transformVOList(fileBos));
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw (DocumentException) e;
            } else {
                throw new DocumentException("附件上传错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }
    }

    /**
     * 复制文件元数据信息
     *
     * @param request     请求对象
     * @param metadataStr 文件业务元数据,JSONObject格式,key范围为 MetadataEnum
     * @param fileKey     文件标志
     * @return BaseRespResult
     */
    @RequestMapping(value = "/copy", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<FileVO> copy(HttpServletRequest request, String metadataStr, String fileKey) {

        //用户ID
        String userId = SecurityUserHolder.getCurrentAccountRealUser().getId();
        //业务元数据添加租户ID
        JSONObject metadata = new JSONObject();
        if (StringUtils.isNotBlank(metadataStr)) {
            metadata = JSON.parseObject(metadataStr);
        }

        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        //调用业务方法
        try {
            //获取新名字
            String newRelName = metadata.containsKey("relName") ? metadata.getString("relName") : null;
            //修改元数据
            FileBO fileBO = documentBusService.copyRelByKey(fileKey, newRelName, metadata, userId);
            return BaseRespResult.successResult(transformVO(fileBO));
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw (DocumentException) e;
            } else {
                throw new DocumentException("修改失败", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }
    }

    /**
     * 更新文件元数据信息
     *
     * @param request     请求对象
     * @param metadataStr 文件业务元数据,JSONObject格式,key范围为 MetadataEnum
     * @param fileKey     文件标志
     * @return BaseRespResult
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<FileVO> update(HttpServletRequest request, String metadataStr, String fileKey) {

        //用户ID
        String userId = SecurityUserHolder.getCurrentAccountRealUser().getId();
        //业务元数据添加租户ID
        JSONObject metadata = new JSONObject();
        if (StringUtils.isNotBlank(metadataStr)) {
            metadata = JSON.parseObject(metadataStr);
        }
        if (metadata.size() == 0 || StringUtils.isBlank(fileKey)) {
            throw new DocumentException("参数错误", DocumentExceptionEnum.DOCUMENT_ERROR);
        }
        //调用业务方法
        try {
            //获取新名字
            String newRelName = metadata.containsKey("relName") ? metadata.getString("relName") : null;
            //修改元数据
            documentBusService.updateMetadataByKey(fileKey, newRelName, metadata, userId);
            FileBO fileBO = documentBusService.selectFileByKey(fileKey);
            return BaseRespResult.successResult(transformVO(fileBO));
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw (DocumentException) e;
            } else {
                throw new DocumentException("修改失败", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }

    }

    /**
     * 查询附件
     *
     * @param request 请求对象
     * @return BaseRespResult
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> select(HttpServletRequest request) {

        //初始化查询对象
        JSONObject metadataQuery = buildMetadataFromRequest(request);
        //调用业务方法
        try {
            //至少包含3个查询条件
            if (metadataQuery.size() < 3) {
                if (metadataQuery.size() < 3) {
                    throw new DocumentException("查询条件至少包含3个！", DocumentExceptionEnum.DOCUMENT_ERROR);
                }
            }
            //保存文件并持久化业务数据
            List<FileBO> fileBos = documentBusService.selectFileByMetadata(metadataQuery);
            return BaseRespResult.successResult(transformVOList(fileBos));
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw e;
            } else {
                throw new DocumentException("附件查询错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }
    }

    /**
     * 根据request获取元数据查询对象
     *
     * @param request 请求对象
     * @return com.alibaba.fastjson.JSONObject
     */
    private JSONObject buildMetadataFromRequest(HttpServletRequest request) {

        //初始化查询对象
        JSONObject metadataQuery = new JSONObject();
        //获取所以元数据枚举
        MetadataEnum[] metadataEnums = MetadataEnum.values();
        //添加查询条件
        for (MetadataEnum metadataEnum : metadataEnums) {
            String code = metadataEnum.getCode();
            String value = request.getParameter(code);
            if (StringUtils.isNotBlank(value)) {
                metadataQuery.put(code, value);
            }
        }
        return metadataQuery;
    }

    /**
     * 文件预览下载
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /preview/{fileKey}
     *
     * @param fileKeyPath 路径参数
     */
    @RequestMapping(value = {"/preview/{fileKey}"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public ResponseEntity<Part> previewByPath(HttpServletRequest request, @PathVariable(name = "fileKey", required = false) String fileKeyPath) {
        return documentBusService.previewAndDownload(request, fileKeyPath, null);
    }

    /**
     * 文件预览下载
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /preview?fileKey={fileKey}
     *
     * @param fileKeyParam 请求参数
     */
    @RequestMapping(value = "/preview", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<Part> previewByParams(HttpServletRequest request, @RequestParam(name = "fileKey", required = false) String fileKeyParam) {
        return documentBusService.previewAndDownload(request, null, fileKeyParam);
    }

    /**
     * 获取文件在线预览
     * <p>
     * 请求方式:GET
     *
     * @param fileKey     请求参数
     * @param previewType 在线预览方式
     */
    @RequestMapping(value = "getPreviewOfficeUrl", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> getPreviewOfficeUrl(HttpServletRequest request, @RequestParam(name = "fileKey", required = false) String fileKey
            , @RequestParam(name = "previewType", required = false) String previewType) {
        return BaseRespResult.successResult(documentBusService.getPreviewOfficeUrl(request, fileKey, previewType));
    }

    /**
     * 校验文件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getFileInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> getFileInfo(HttpServletRequest request) {
        String[] arr = {"keys"};
        String result = StringUtil.checkEmpty(arr, request);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        String fileKeys = StringUtil.getStringParameter(request, "keys");
        return BaseRespResult.successResult(documentBusService.getFileInfo(fileKeys));
    }

    /**
     * 校验文件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "checkFile", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> checkFile(HttpServletRequest request) {
        String[] arr = {"fileKey"};
        String result = StringUtil.checkEmpty(arr, request);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        String fileKey = StringUtil.getStringParameter(request, "fileKey");
        boolean isExistFile = documentBusService.existsOnDB(fileKey);
        if (!isExistFile) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("document.file.not.exist"));
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("document.file.exist"));
    }

    /**
     * 文件预览下载
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /down/{fileKey}
     *
     * @param fileKeyPath 路径参数
     */
    @RequestMapping(value = "/down/{fileKey}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<Part> downloadByPath(HttpServletRequest request, @PathVariable(name = "fileKey", required = false) String fileKeyPath) {
        return documentBusService.previewAndDownload(request, fileKeyPath, null);
    }

    /**
     * 文件预览下载
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /down?fileKey={fileKey}
     *
     * @param fileKeyParam 请求参数
     */
    @RequestMapping(value = "/down", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<Part> downloadByParams(HttpServletRequest request, @RequestParam(name = "fileKey", required = false) String fileKeyParam) {
        return documentBusService.previewAndDownload(request, null, fileKeyParam);
    }

    /**
     * 预览文件返回文本
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /previewTxt/{fileKey}
     * /previewTxt?fileKey={fileKey}
     *
     * @param fileKeyPath 路径参数
     */
    @RequestMapping(value = "/previewTxt/{fileKey}", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> previewTxtByPath(@PathVariable(name = "fileKey", required = false) String fileKeyPath) {
        return documentBusService.previewTxt(fileKeyPath, null);
    }

    /**
     * 预览文件返回文本
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /previewTxt?fileKey={fileKey}
     *
     * @param fileKeyParam 请求参数
     */
    @RequestMapping(value = "/previewTxt", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> previewTxtByParams(@RequestParam(name = "fileKey", required = false) String fileKeyParam) {
        return documentBusService.previewTxt(null, fileKeyParam);
    }

    /**
     * 获取文件缩略图 仅支持图片
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /thumbnail/{fileKey}
     *
     * @param fileKeyPath 路径参数
     */
    @RequestMapping(value = "/thumbnail/{fileKey}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<InputStream> thumbnailByPath(HttpServletRequest request, @PathVariable(name = "fileKey", required = false) String fileKeyPath) {
        logger.info("fileKeyPath     " + fileKeyPath);
        return documentBusService.thumbnail(request, fileKeyPath, null);
    }

    /**
     * 获取文件缩略图 仅支持图片
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /thumbnail?fileKey={fileKey}
     *
     * @param fileKeyParam 请求参数
     */
    @RequestMapping(value = "/thumbnail", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<InputStream> thumbnailByParams(HttpServletRequest request, @RequestParam(name = "fileKey", required = false) String fileKeyParam) {
        return documentBusService.thumbnail(request, null, fileKeyParam);
    }

    /**
     * 文件打包下载
     * <p>
     * 请求方式:
     * /downZip?fileKeys={fileKeys}
     *
     * @param fileKeys 文件唯一标识集合;json数组格式字符串
     * @param zipName  压缩包名称，为空时使用当前时间戳
     */
    @RequestMapping(value = "/downZip", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<Part> downZip(@RequestParam(name = "fileKeys", required = false) String fileKeys,
                                        @RequestParam(name = "zipName", required = false) String zipName) {
        try {
            if (StringUtils.isBlank(fileKeys)) {
                throw new DocumentException("参数错误", DocumentExceptionEnum.DOCUMENT_ERROR);
            }
            //fileKeys转换list
            List<String> fileKeyList = Arrays.asList(fileKeys.split(","));
            InputStream zipInputStream = documentBusService.buildZip(fileKeyList);
            String fileName = URLEncoder.encode(StringUtils.isNotBlank(zipName) ? zipName : System.currentTimeMillis() + ".zip", "UTF-8");
            ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.ok();
            bodyBuilder.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
            return bodyBuilder.body(new InputstreamContentTypePart(fileName, zipInputStream, ContentTypeSuffixEnum.S_zip.getContentType()));
        } catch (DocumentException e) {
            throw e;
        } catch (Exception e) {
            throw new DocumentException("打包下载失败", DocumentExceptionEnum.DOCUMENT_ERROR, e);
        }

    }

    /**
     * 获取文件属性
     *
     * @param fileKey 文件唯一标识
     * @return com.je.core.result.<com.je.paas.document.vo.FileAttributesVO>
     */
    @RequestMapping(value = "/attributes", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<FileVO> attributes(String fileKey) {
        if (StringUtils.isBlank(fileKey)) {
            throw new DocumentException("参数错误", DocumentExceptionEnum.DOCUMENT_ERROR);
        }
        try {
            //初始化返回参数
            FileVO vo = transformVO(documentBusService.selectFileByKey(fileKey));
            return BaseRespResult.successResult(vo);
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw (DocumentException) e;
            } else {
                throw new DocumentException("文件信息查找错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }
    }

    /**
     * 删除附件
     *
     * @param fileKeys 附件唯一标识
     * @return com.je.core.result.BaseRespResult<java.lang.String>
     */
    @RequestMapping(value = "/del", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> del(String fileKeys) {
        if (StringUtils.isBlank(fileKeys)) {
            throw new DocumentException("参数错误", DocumentExceptionEnum.DOCUMENT_ERROR);
        }
        try {
            //用户ID
            String userId = SecurityUserHolder.getCurrentAccountRealUser().getId();
            //删除
            documentBusService.delFilesByKey(Arrays.asList(fileKeys.split(",")), userId);
            return BaseRespResult.successResult("成功");
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw (DocumentException) e;
            } else {
                throw new DocumentException("文件信息查找错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }

    }

    /**
     * 删除附件（通过 fileKeys 物理删除文件 【先看文件在其他地方有没有引用，如果有的话，只删除引用信息。如果没有删除引用信息，同时删除 服务器文件】）
     *
     * @param fileKeys 附件唯一标识
     * @return com.je.core.result.BaseRespResult<java.lang.String>
     */
    @RequestMapping(value = "/deleteByFileKeys", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> deleteByFileKeys(String fileKeys) {
        if (StringUtils.isBlank(fileKeys)) {
            throw new DocumentException("参数错误", DocumentExceptionEnum.DOCUMENT_ERROR);
        }
        try {
            //用户ID
            String userId = SecurityUserHolder.getCurrentAccountRealUser().getId();
            //删除
            documentBusService.deleteByFileKeys(Arrays.asList(fileKeys.split(",")), userId);
            return BaseRespResult.successResult("成功");
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw (DocumentException) e;
            } else {
                throw new DocumentException("文件信息错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }

    }

    @RequestMapping(value = "/selectMetaDataByFileKey", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult selectMetaDataByFileKey(String fileKey) {
        if (StringUtils.isBlank(fileKey)) {
            throw new DocumentException("参数错误", DocumentExceptionEnum.DOCUMENT_ERROR);
        }
        try {

            List<Map<String, Object>> maps = fileRelService.selectMetaDataByFileKey(fileKey);
            JSONObject jsonObject = new JSONObject();
            if (maps != null && maps.size() > 0) {
                Map<String, Object> metaDataMap = maps.get(0);
                jsonObject.put("name", metaDataMap.get("name") == null ? "" : metaDataMap.get("name").toString());
                jsonObject.put("type", metaDataMap.get("suffix") == null ? "" : metaDataMap.get("suffix").toString());
                jsonObject.put("fileSize", metaDataMap.get("fileSize") == null ? "" : (Long) metaDataMap.get("fileSize") / 1024);
                jsonObject.put("createUser", metaDataMap.get("createUser") == null ? "" : metaDataMap.get("createUser").toString());
                jsonObject.put("department", metaDataMap.get("department") == null ? "" : metaDataMap.get("department").toString());
                jsonObject.put("createTime", metaDataMap.get("createTime") == null ? "" : metaDataMap.get("createTime").toString().substring(0, metaDataMap.get("createTime").toString().length() - 2));
            }
            return BaseRespResult.successResult(jsonObject);
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw (DocumentException) e;
            } else {
                throw new DocumentException("文件信息错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
            }
        }

    }

    /**
     * BO转VO
     *
     * @param fileBos BO集合
     * @return java.util.List<com.je.paas.document.vo.FileVO>
     */
    private List<FileVO> transformVOList(List<FileBO> fileBos) {
        //构建VO
        List<FileVO> fileVOS = new ArrayList<>();
        for (FileBO fileBO : fileBos) {
            fileVOS.add(transformVO(fileBO));
        }
        return fileVOS;
    }

    /**
     * BO转VO
     *
     * @param fileBO BO实体
     * @return java.util.List<com.je.paas.document.vo.FileVO>
     */
    private FileVO transformVO(FileBO fileBO) {

        FileVO vo = new FileVO();
        vo.setFileKey(fileBO.getFileKey());
        vo.setRelName(fileBO.getRelName());
        vo.setFullUrl(fileBO.getFullUrl());
        vo.setSuffix(fileBO.getSuffix());
        vo.setHasThumbnail(StringUtils.isNotBlank(fileBO.getThumbnail()));
        vo.setSize(fileBO.getSize());
        vo.setCreateTime(fileBO.getCreateTime());
        vo.setCreateTimeStr(DateUtils.formatDateTime(fileBO.getCreateTime()));
        vo.setDicCode(fileBO.getDicCode());
        vo.setDicId(fileBO.getDicId());
        vo.setDicName(fileBO.getDicName());
        vo.setRemarks(fileBO.getRemarks());
        vo.setCreateUserDeptName(fileBO.getCreateUserDeptName());
        vo.setCreateUserName(fileBO.getCreateUserName());
        return vo;
    }

}